import * as Koa from 'koa';
import * as bodyparser from 'koa-bodyparser';
import * as logger from 'koa-logger';

// import routerLoader from './scanRouter';
import Register from './register';
export interface Middleware {
    (ctx: any, next: any): void;
}

export interface Props {
    port?: number;
    middlewares?: Array<Middleware>;
    routerPath?: string;
    controllerPath?: string;
    servicePath?: string;
    routerPrefix?: string;
}

const _DEFAULT_PROPS: Props = {
    port: 3000,
    middlewares: []
};

const _DEFAULT_MIDDLEWARES = [bodyparser(), logger()];

export default class extends Koa {
    private props: Props;
    constructor(props: Props) {
        super();
        let _props = { ..._DEFAULT_PROPS, ...props };
        _props.middlewares = _props.middlewares || [];
        _props.middlewares = [..._DEFAULT_MIDDLEWARES, ..._props.middlewares];
        this.props = _props;
        this.registerMiddleware(this.props.middlewares || []);
        this.registerRouter();
        this.listen(this.props.port, () => {
            console.log(`已启动---监听端口号为：---${this.props.port}---`);
        });
    }
    public injectionMiddle(middleware: Middleware|Middleware[]): void {
        this.registerMiddleware(middleware);
    }
    private registerMiddleware(middleware: Middleware|Middleware[]): void {
        if (Array.isArray(middleware)) {
            middleware.map(item => (typeof item === 'function' && this.use(item)));
        } else {
            typeof middleware === 'function' && this.use(middleware);
        }
    }
    private registerRouter(): void{
        const { routerPath, controllerPath, servicePath, routerPrefix } = this.props;
        if (!routerPath || !controllerPath || !servicePath) {
            throw new Error('请检查路劲参数是否完整');
        } else {
            const register = new Register({ routerPath, controllerPath, servicePath });
            const route = register.route;
            routerPrefix && route.prefix(routerPrefix);
            this.use(route.routes());
        }
    }
}